import { Component, OnInit } from '@angular/core';
import {InventoryService} from "../inventory.service";
import {ConfirmationService} from "primeng/primeng";
import {ActivatedRoute, Router} from "@angular/router";
import {StorageService} from "../../services/storage.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {timeValidator} from "../../validator/validators";
import {BasePage} from "../../base.page";
import {MessageService} from "primeng/components/common/messageservice";
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-borrow',
  templateUrl: './borrow.component.html',
  styleUrls: ['./borrow.component.scss']
})
export class BorrowComponent extends BasePage implements OnInit {
  cols;
  zh: any;                               // 汉化
  showBorrowItems: boolean = false;      //借用物品弹框
  statusNames = [];
  dataSource = [];
  editDataSource = [];
  editInspections = [];
  totalRecords;
  selectInsepections = [];
  inspections = [];
  submitData;
  borrowData = [];
  beginTime: Date;                   // 当日系统时间
  endTime: Date;
  nowDate;
  button: boolean = false;
  coles;
  somecols;
  inventoryborrowForm: FormGroup;
  viewState;//保存当前的操作状态
  personalData = [];
  state;
  updatecols;
  update;
  constructor( private inventoryService: InventoryService,
               public confirmationService: ConfirmationService,
               public messageService:MessageService,
               private storageService:StorageService,
               private router:Router,
               private route:ActivatedRoute,
               private fb: FormBuilder,
               private eventBusService: EventBusService
               ) {
    super(confirmationService,messageService,)
    this.inventoryborrowForm = this.fb.group({
      'sid': [''],
      'type': [''],
      'people': [''],
      'inspectiondepartment': [''],
      'inspectiondepartmentname': [''],
      timeGroup:this.fb.group({
        startTime: ['', Validators.required],
        endTime: ['', Validators.required],
      },{validator:timeValidator}),
      'remarks':['', Validators.required],
    })
  }

  ngOnInit() {
    this.nowDate = new Date();
    this.button = true;
    this.viewState = 'apply'
    this.beginTime = new Date();
    this.cols = [
      {field: 'sid', header: '编号' ,editable:false},
      {field: 'name', header: '名称' ,editable:false},
      {field: 'catagory', header: '分类' ,editable:false},
      {field: 'brand', header: '品牌' ,editable:false},
      {field: 'model', header: '型号' ,editable:false},
      {field: 'specification', header: '规格' ,editable:false},
      {field: 'quantity', header: '数量' ,editable:true},
    ];
    this.update = [
      {field: 'sid', header: '编号' ,editable:false},
      {field: 'name', header: '名称' ,editable:false},
      {field: 'catagory', header: '分类' ,editable:false},
      {field: 'brand', header: '品牌' ,editable:false},
      {field: 'model', header: '型号' ,editable:false},
      {field: 'specification', header: '规格' ,editable:false},
      {field: 'balance', header: '数量' ,editable:true},
    ];
    this.coles = [
      {field: 'sid', header: '编号' ,editable:false},
      {field: 'name', header: '名称' ,editable:false},
      {field: 'catagory', header: '分类' ,editable:false},
      {field: 'brand', header: '品牌' ,editable:false},
      {field: 'model', header: '型号' ,editable:false},
      {field: 'specification', header: '规格' ,editable:false},
      {field: 'application_quantity', header: '申请数量' ,editable:false},
      {field: 'quantity', header: '实际借用数量' ,editable:false},
      {field: 'balance', header: '剩余归还数' ,editable:false},
    ];
    this.somecols = [
      {field: 'sid', header: '编号' ,editable:false},
      {field: 'name', header: '名称' ,editable:false},
      {field: 'catagory', header: '分类' ,editable:false},
      {field: 'brand', header: '品牌' ,editable:false},
      {field: 'model', header: '型号' ,editable:false},
      {field: 'specification', header: '规格' ,editable:false},
      {field: 'balance', header: '待归还数' ,editable:false},
      {field: 'return_quantity', header: '本次归还' ,editable:true},
    ];

    this.updatecols = [
      {field: 'sid', header: '编号' ,editable:false},
      {field: 'name', header: '名称' ,editable:false},
      {field: 'catagory', header: '分类' ,editable:false},
      {field: 'brand', header: '品牌' ,editable:false},
      {field: 'model', header: '型号' ,editable:false},
      {field: 'specification', header: '规格' ,editable:false},
      {field: 'application_quantity', header: '申请数量' ,editable:false},
      {field: 'quantity', header: '实际出库数量' ,editable:true},
      {field: 'onhand_quantity', header: '当前库存' ,editable:false},

    ];
    this.zh = {
      firstDayOfWeek: 1,
      dayNames: [ "周一","周二","周三","周四","周五","周六","周日" ],
      dayNamesShort: [ "一","二","三","四","五","六","七" ],
      dayNamesMin: [ "一","二","三","四","五","六","七" ],
      monthNames: [ "一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月" ],
      monthNamesShort: [ "一","二","三","四","五","六","七","八","九","十","十一","十二" ],
    };
    this.statusNames = [
      {label: '借用', value: '借用'},
    ]
    this.submitData = {
      "sid": "",
      "type": this.statusNames[0]['value'],
      "return_time": "",
      "create_time":"",
      "urgency": "",
      "remarks": "",
      "org": "",
      "inventories": []
    }
    this.submitData.create_people = this.storageService.getUserName('userName');
    this.querylogin();
    this.route.queryParams.subscribe(params=>{
      this.viewState = 'apply';
      if(params['sid']&&params['state'] && params['title']){
        this.viewState = params['state'];
        this.inventoryService.outboundShow(params['sid']).subscribe(data=>{
          this.borrowData = data;
          // console.log(this.borrowData);
          this.editDataSource = this.borrowData['inventories']?this.borrowData['inventories']:[];
          if(!this.editDataSource){
            this.editDataSource = [];
            this.editInspections =[];
            this.totalRecords = 0;
          }
          this.totalRecords = this.editDataSource.length;
          this.editInspections = this.editDataSource.slice(0,10);
        })
      }
    })
  }

  goBack() {
    let sid =  this.borrowData['sid'];
    // this.currentMaterial['status'] = "";
    // this.eventBusService.borrow.next(this.currentMaterial['status']);
    this.borrowData['status'] = "";
    this.eventBusService.borrow.next(this.borrowData['status']);
    this.router.navigate(['../outbound'],{queryParams:{sid:sid,state:'viewDetail',title:'借用总览'},relativeTo:this.route})
  }

  //查询登录人
  querylogin(){
    this.inventoryService.queryPersonal().subscribe(data=>{
      this.personalData = data;
      this.submitData['org'] = this.personalData['organization']
    });
  }
  // 提交
  addStorageSubmint(submitData,dataSource){
    let inventories = [];
    for(let i = 0;i<dataSource.length;i++){
      let temp = dataSource[i];
      let obj = {};
      obj['pn'] = temp['pn'];
      obj['sid'] = temp['sid'];
      obj['quantity'] = temp['quantity'];
      obj['location'] = temp['location'];
      obj['location_id'] = temp['location_id'];
      obj['keeper'] = temp['keeper'];
      obj['keeprer_pid'] = temp['keeprer_pid'];
      inventories.push(obj);
    }
    submitData.inventories = inventories;
    this.inventoryService.addDelivery(submitData).subscribe(()=>{
      this.router.navigate(['../outbound'],{queryParams:{title:'借用总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  //保存
  addDeviceSave(submitData,dataSource){
    let inventories = [];
    for(let i = 0;i<dataSource.length;i++){
      let temp = dataSource[i];
      let obj = {};
      obj['pn'] = temp['pn'];
      obj['sid'] = temp['sid'];
      obj['location'] = temp['location'];
      obj['location_id'] = temp['location_id'];
      obj['keeper'] = temp['keeper'];
      obj['keeprer_pid'] = temp['keeprer_pid'];
      obj['quantity'] = temp['quantity'];
      inventories.push(obj);
    }
    submitData.inventories = inventories;
    this.inventoryService.queryDeliverySave(submitData).subscribe(data=>{
      this.router.navigate(['../outbound'],{queryParams:{title:'借用总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err;
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  //修改保存方法
  updateDeviceSave(submitData,dataSource){
    let inventories = [];
    for(let i = 0;i<dataSource.length;i++){
      let temp = dataSource[i];
      let obj = {};
      obj['pn'] = temp['pn'];
      obj['sid'] = temp['sid'];
      obj['location'] = temp['location'];
      obj['location_id'] = temp['location_id'];
      obj['keeper'] = temp['keeper'];
      obj['keeprer_pid'] = temp['keeprer_pid'];
      obj['quantity'] = temp['quantity'];
      obj['delivery_sid'] = temp['delivery_sid'];
      obj['borrower'] = temp['borrower'];
      obj['borrower_pid'] = temp['borrower_pid'];
      obj['return_quantity'] = temp['return_quantity'];
      obj['balance'] = temp['balance'];
      obj['name'] = temp['name'];
      obj['catagory'] = temp['catagory'];
      obj['supplier'] = temp['supplier'];
      obj['brand'] = temp['brand'];
      obj['model'] = temp['model'];
      obj['specification'] = temp['specification'];
      inventories.push(obj);
    }
    submitData.inventories = inventories;
    this.inventoryService.queryDeliveryMod(submitData).subscribe(data=>{
      this.router.navigate(['../outbound'],{queryParams:{title:'借用总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  deleteStorage(){
    for(let i = 0;i<this.selectInsepections.length;i++){
      for(let j = 0;j<this.dataSource.length;j++){
        if(this.selectInsepections[i]['sid']===this.dataSource[j]['sid']){
          this.dataSource.splice(j,1);
          this.totalRecords = this.dataSource.length;
          this.inspections = this.dataSource.slice(0,10);
          this.selectInsepections = [];
        }
      }
    }
  }
  updatedeleteStorage(){
    for(let i = 0;i<this.selectInsepections.length;i++){
      for(let j = 0;j<this.editDataSource.length;j++){
        if(this.selectInsepections[i]['sid']===this.editDataSource[j]['sid']){
          this.editDataSource.splice(j,1);
          this.totalRecords = this.editDataSource.length;
          this.editInspections = this.editDataSource.slice(0,10);
          this.selectInsepections = [];
        }
      }
    }
  }
  loadCarsLazy(event) {
    setTimeout(() => {
      if(this.dataSource) {
        this.inspections = this.dataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  addDev(metail){
    this.showBorrowItems = false;
    // let hashTable = {};
    // let newArr = [];
    // for(let i=0,l=metail.length;i<l;i++) {
    //   if(!hashTable[metail[i]]) {
    //     hashTable[metail[i]] = true;
    //     newArr.push(metail[i]);
    //   }
    //   return newArr;
    // }
    for(let i = 0;i<metail.length;i++){
      this.dataSource.push(metail[i]);
      this.editDataSource.push(metail[i])
    }
    this.totalRecords = this.dataSource.length;
    this.totalRecords = this.editDataSource.length;
    this.inspections = this.dataSource.slice(0,10);
    console.log(this.inspections)
    this.editInspections = this.editDataSource.slice(0,10);
  }
  formSubmit(){
    if(this.viewState === 'apply'){
      this.addStorageSubmint(this.submitData,this.dataSource);
    }else if(this.viewState === 'update'){
      this.addStorageSubmint(this.borrowData,this.editDataSource);
    }
  }
  formSave(){
    if(this.viewState === 'apply'){
      this.addDeviceSave(this.submitData,this.dataSource);
    }else if(this.viewState === 'update'){
      this.updateDeviceSave(this.borrowData,this.editDataSource);
    }
  }
  startTimeSelected(t) {
    this.endTime = t;
  }
  showBorrowItemsMask(state){
    this.state = 'apply';
    this.showBorrowItems = !this.showBorrowItems;
  }
  closeBorrowItemsMask(bool){
    this.showBorrowItems = bool;
  }
  returnBorrow(){
    let obj = {};
    obj['sid']= this.borrowData['sid'];
    obj['inventories'] = this.selectInsepections;
    console.log(this.selectInsepections)
    this.confirmationService.confirm({
      message: '是否归还?',
      rejectVisible:true,
      accept: () => {
        this.inventoryService.someDeliveryReturn(obj).subscribe(data=>{
          this.selectInsepections = [];
          this.router.navigate(['../outbound'],{queryParams:{title:'借用总览'},relativeTo:this.route})

        },(err:Error)=>{
          this.toastError(err)
        })
      },
      reject:() =>{}
    })
  }

  editloadCarsLazy(event) {
    setTimeout(() => {
      if(this.editDataSource) {
        this.editInspections = this.editDataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  //确认出库
  sureApproved(){
    let inventories = [];
    for(let i = 0;i<this.selectInsepections.length;i++){
      let temp = this.selectInsepections[i];
      inventories.push(temp)
    }
    let queryModel = {
      "sid":this.borrowData['sid'],
      "inventories":inventories
    }
    this.eventBusService.borrow.next(this.borrowData['status']);
    this.confirmationService.confirm({
      message: '确定出库吗?',
      rejectVisible:true,
      accept: () => {
        this.inventoryService.queryBorrowSure(queryModel).subscribe(()=>{
          this.borrowData['status'] = "";
          this.eventBusService.borrow.next(this.borrowData['status']);
          this.router.navigate(['../outbound'],{relativeTo:this.route})

        },(err:Error)=>{
          this.confirmationService.confirm({
            message: err['message'],
            rejectVisible:false,
          })
        })
      },
      reject:() =>{}
    })
  }
}
